﻿using System;
using System.Threading;

namespace _2___Clock {
    public class Clock {
        private Boolean runningState;
        private Thread timeThread;
        public delegate void TickHandler(object sender);
        public delegate void AlarmHandler(object sender);
        public event TickHandler OnTick;
        public event AlarmHandler OnAlarm;

        private int time;
        public int alarmTime;

        public Clock(int time) {
            this.time = time;
            Action action = delegate () {
                while (runningState) {
                    AddTime();
                    Thread.Sleep(1000);
                }
            };
            timeThread = new Thread(new ThreadStart(action));
            runningState = false;
        }
        public Clock(int time, int alarmTime) : this(time) {
            this.alarmTime = alarmTime;
        }
        public String GetTime() {
            return (time / 60 / 60).ToString().PadLeft(2, '0')
                + ":"
                + (time / 60 % 60).ToString().PadLeft(2, '0')
                + ":"
                + (time % 60).ToString().PadLeft(2, '0');
        }
        public void AddTime() {
            time = (time + 1) % 86400;
            if (time == alarmTime) {
                if (OnAlarm != null) {
                    OnAlarm(this);
                }
            }
            else {
                if (OnTick != null) {
                    OnTick(this);
                }
            }
        }
        public void StartClock() {
            runningState = true;
            timeThread.Start();
        }
        public void StopClock() {
            runningState = false;
        }
    }
    class Program {
        static void Main(string[] args) {
            Clock clock = new Clock(86395, 5);
            clock.OnTick += Clock_OnTick;
            clock.OnAlarm += Clock_OnAlarm;
            clock.StartClock();
            Thread.Sleep(20000);
            clock.StopClock();
        }

        private static void Clock_OnAlarm(object sender) {
            if (sender is Clock) {
                Console.WriteLine($"[{(sender as Clock).GetTime()}] ReoReoReo...");
            }
        }

        private static void Clock_OnTick(object sender) {
            if (sender is Clock) {
                Console.WriteLine($"[{(sender as Clock).GetTime()}] Tick.");
            }
        }
    }
}
